package com.framework.websocket.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单控制器 - 演示订单状态订阅
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 更新订单状态
     * 
     * 使用示例：
     * POST /api/order/ORD123456/status?status=PAID&remark=支付成功
     */
    @PostMapping("/{orderId}/status")
    public Map<String, Object> updateOrderStatus(
            @PathVariable String orderId,
            @RequestParam String status,
            @RequestParam(required = false) String remark) {
        
        Map<String, Object> orderStatus = new HashMap<>();
        orderStatus.put("orderId", orderId);
        orderStatus.put("status", status);
        orderStatus.put("statusName", getStatusName(status));
        orderStatus.put("remark", remark);
        orderStatus.put("updateTime", LocalDateTime.now().toString());
        
        // 保存到Redis - 键前缀必须是 "order:status:"
        String key = "order:status:" + orderId;
        redisTemplate.opsForValue().set(key, orderStatus);
        
        // 如果是特定状态，可以设置过期时间
        if ("COMPLETED".equals(status) || "CANCELLED".equals(status)) {
            // 已完成或已取消的订单，7天后过期
            redisTemplate.expire(key, 7, java.util.concurrent.TimeUnit.DAYS);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "订单状态已更新");
        result.put("data", orderStatus);
        return result;
    }
    
    private String getStatusName(String status) {
        switch (status) {
            case "CREATED":
                return "已创建";
            case "PAID":
                return "已支付";
            case "SHIPPED":
                return "已发货";
            case "DELIVERED":
                return "已送达";
            case "COMPLETED":
                return "已完成";
            case "CANCELLED":
                return "已取消";
            case "REFUNDED":
                return "已退款";
            default:
                return "未知状态";
        }
    }
}